import { capitalize, get, set } from 'lodash-es'
import { ComponentNameEnum } from "../types"
import type { ColProps, FormSchema } from "../types"


export const setTextPlaceholder = (item: FormSchema) => {
  const textMap = [ComponentNameEnum.INPUT]
  if (textMap.includes(item.component as ComponentNameEnum)) {
    return { placeholder: '请输入' }
  }
  return {}
}
export const setGridProp = (col: ColProps = {}) => {
  const colProps = { ...(col.span ? {} : { xs: 24, sm: 12, md: 12, lg: 12, xl: 12 }), ...col }
  return colProps
}

export const setComponentProps = (item: FormSchema): Record<string, any> => {
  // 处理事件
  const onEvents = (item.componentProps as any)?.on || {}
  const newOnEvents: Record<string, any> = {}
  for (const key in onEvents) {
    if (onEvents[key]) {
      newOnEvents[`on${capitalize(key)}`] = (...args: any[]) => {
        onEvents[key](...args)
      }
    }
  }
  const componentProps: Record<string, any> = { ...item.componentProps, ...newOnEvents }
  if (componentProps.on) {
    delete componentProps.on
  }
  return componentProps
}

/**
 *
 * @param schema Form表单结构化数组
 * @param formModel FormMoel
 * @returns FormMoel
 * @description 生成对应的formModel
 */
export const initModel = (schema: FormSchema[], formModel: Record<string, any>): Record<string, any> => {
  const model = { ...formModel }
  schema.map(v => {
    if (v.remove) {
      delete model[v.field]
    }
    const fileValue = get(model, v.field)
    set(model, v.field, fileValue !== undefined ? fileValue : v.value !== undefined ? v.value : undefined )
  })
  return model
}
